#include "ControlManager.h"
#include "json.h"
#include "x_time.h"
#include "x_sdk_def.h"
#include "x_string.h"
#include "AdapterManager.h"

static const char *http_end = "\r\n\r\n";

CControlManager::CControlManager()
{

}

CControlManager::~CControlManager()
{

}

int CControlManager::StartService(int nPort)
{
	return Start(nPort);
}

int CControlManager::StopService()
{
	return Stop();
}

///CXService
int CControlManager::OnAccept(int nSocket)
{
	return J_OK;
}

int CControlManager::OnRead(int nSocket)
{
 	J_OS::CTCPSocket ReadSocket(nSocket);
	char read_buff[2048] = {0};
	int read_ret = 0;
	int totle_recv = 0;
	char *p = NULL;
	do
	{
		read_ret = ReadSocket.Read(read_buff + totle_recv, sizeof(read_buff));
		if (read_ret < 0)
		{
			return J_SOCKET_ERROR;
		}
		//J_OS::LOGINFO(read_buff);
		if (strstr(read_buff, "HTTP") == NULL && strstr(read_buff, "POST") == NULL)
			return J_OK;

		totle_recv += read_ret;
	} while((p = strstr(read_buff, http_end)) == NULL);

	CXString x_string(read_buff);
	CXInteger32 i_command("Content-Length: ", "\r\n");
	x_string >> i_command;

	int body_recv = i_command() - (totle_recv - (p - read_buff) - 4);
	while (body_recv > 0)
	{
		read_ret = ReadSocket.Read(read_buff + totle_recv, sizeof(read_buff));
		if (read_ret < 0)
		{
			return J_SOCKET_ERROR;
		}
		totle_recv += read_ret;
		body_recv -= read_ret;
	}
	char send_buff[1024] = {0};
	int nRet = m_rymcHelper.ProcessMcCommand(read_buff, send_buff);
	ReadSocket.Write_n(send_buff, nRet);

	return J_OK;
}

int CControlManager::OnWrite(int nSocket)
{
	usleep(1000);
	return J_OK;
}

int CControlManager::OnBroken(int nSocket)
{
	return J_OK;
}
